//
//  KDChildAutoMoController.m
//  WangJingApp
//
//  Created by 魏强 on 17/11/1.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDChildAutoMoController.h"
#import "KDDetailSubscribController.h"
#import "KDTabBarController.h"
#import "KDSubscribCell.h"
#import "KDSubscribCellModel.h"
#import "KDAutoRequestTool.h"
#import "KDGetMonitorNewsParam.h"
#import "KDGetSubscribeListResult.h"
#import "KDSubscribCell.h"
#import "KDSubscribCellModel.h"
#import "KDReportController.h"
#import "KDPatrolgetReportParam.h"
#import "KDCollectRequestTool.h"
#import "KDFavorTypeListResult.h"
#import "AlertTableView.h"
#import "KDBaseBoard.h"
#import "KDBaseBoardModel.h"
#import "KGDislikeView.h"
#import "KDDeleteNewsParam.h"

@interface KDChildAutoMoController ()<UITableViewDelegate,UITableViewDataSource,KDSubscribCellDelegate, KDDetailSubscribControllerDelegate,KDReportControllerDelegate,UISearchBarDelegate, baseboardDelegate>
/**  <#Description#> */
@property (nonatomic, weak) UITableView *currentTabV;

/**  所有数据汇总 */
@property (nonatomic, strong) NSArray *infoArr;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;

@property (nonatomic, weak) KDBaseBoard *baseView;
/** 右边弹出的选择界面的遮盖*/
@property (nonatomic, weak) UIButton *cover;

/**  <#Description#> */
@property (nonatomic, strong) KDGetMonitorNewsParam *param;
@property (nonatomic, retain) NSDateFormatter *fmt;

@end
static CGFloat const searchViewH = 44;

static CGFloat const chooseBtnW = 55;
@implementation KDChildAutoMoController
#pragma mark - 懒加载区
- (KDGetMonitorNewsParam *)param
{
    if (!_param) {
        _param = [[KDGetMonitorNewsParam alloc]init];
        _param.method = @"earlywaring/queryEarlyWaringInfo";
        _param.earlyWaringId = [NSString stringWithFormat:@"%ld",self.model.ID];
        _param.groupId = [NSString stringWithFormat:@"%ld",self.model.group_id];
        KDAccount *account = [KDAccountTool account];
        _param.provinceId = [NSString stringWithFormat:@"%ld",account.provinceId];
        _param.cityId = [NSString stringWithFormat:@"%ld",account.cityId];
        _param.is_polymer = @"1";
        _param.limit = @"20";
//        _param.countyId = [NSString stringWithFormat:@"%ld",account.countyId];
        
        
        //        _param.
        //        _param
    }
    return _param;
}
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    }
    return _fmt;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}

- (void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        [self.currentTabV.header beginRefreshing];
    }
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setupsearchView];
    
    [self setUpTableView];
}
#pragma mark - 板块布置区
- (void)setupsearchView{
    //1.创建底部view
    UIView *underView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, searchViewH)];
    [self.view addSubview: underView];
    
    //2.创建筛选按钮
    UIButton *chooseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chooseBtn.frame = CGRectMake(screenW - chooseBtnW, 0, chooseBtnW, searchViewH);
    [chooseBtn setTitle:@"筛选" forState:UIControlStateNormal];
    chooseBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [chooseBtn setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
    [chooseBtn addTarget:self action:@selector(chooseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    chooseBtn.backgroundColor = [UIColor whiteColor];
    [chooseBtn setTitleColor:WQColor(0, 193, 142) forState:UIControlStateNormal];;
    //    self.<#btn#> = <#btn#>;
    [underView addSubview:chooseBtn];
    
    
    //2.创建searchbar
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(5, 5, screenW - chooseBtnW - 10, searchViewH - 5*2)];
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    //    searchBar.layer.borderColor = WQColor(36, 172, 83).CGColor;
    //    searchBar.layer.borderWidth = 1;
    //    searchBar.layer.cornerRadius = 3;
    searchBar.placeholder = @"请输入关键词";
    searchBar.delegate = self;
    //    [searchBar addTarget:searchBar action:@selector(searchBarClick)];
    [underView addSubview:searchBar];
}
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , searchViewH, screenW, self.view.height -88 - searchViewH) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = Cell_h;
    if (!iOS7) {
        tableView.estimatedRowHeight = Cell_h;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    UINib *xib =[UINib nibWithNibName:@"KDSubscribCell" bundle:nil] ;
    [tableView registerNib:xib forCellReuseIdentifier:@"KDSubscribCell"];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}

/***  设置右边选择页面*/
-(void)setUpRightChoosePage
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!self.cover) {
        //加蒙板
        UIButton *cover = [[UIButton alloc]initWithFrame:window.bounds];
        self.cover = cover;
        cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        [window addSubview:_cover];
    }
    self.cover.frame = window.bounds;
    //创建底板
    if (!self.baseView) {
        KDBaseBoard *baseView = [KDBaseBoard baseboard];
        self.baseView = baseView;
        baseView.delegate = self;
        baseView.x = screenW;
        baseView.y = 64;
        baseView.height = screenH - baseView.y ;
        baseView.width = screenW - screenW*0.175;
        //        baseView.mainPageType = self.mainType;
        
        [_cover addSubview:baseView];
    }
    //    KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
    
    //    _baseView.showReginType = self.regionType;
    _baseView.height = screenH - _baseView.y ;
    _baseView.width = screenW - screenW*0.175;
    [UIView animateWithDuration:0.4 animations:^{
        _baseView.x = screenW*0.175;
    }];
}
#pragma mark - 事件点击区
/**
 *  筛选按钮被点击了
 *
 *  @param chooseBtn <#chooseBtn description#>
 */
- (void)chooseBtnClick:(UIButton *)chooseBtn{
    
    if (!chooseBtn.selected) {
        
        //设置右边的选择页面
        [self setUpRightChoosePage];
    } else
    {
        [self coverClick:self.cover];
    }
    chooseBtn.selected = chooseBtn.selected;
}

/***  去掉蒙板及右边页 */
- (void)coverClick:(UIButton *)cover
{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.x = screenW;
        
    } completion:^(BOOL finished) {
        
        self.cover.frame = CGRectMake(0, 0, 0, 0);
        //        self.rightBarBtn.selected = NO;
        
    }];
    
}


#pragma mark - 网络请求区
- (void)loadDetailData{
    self.page = @"1";
    //    KDSubscribeListParam *param = [[KDSubscribeListParam alloc]init];
    //    self.param.method = @"earlywaring/queryEarlyWaringPushInfo";
    self.param.page = self.page;
    //    self.param.aboutType = [NSString stringWithFormat:@"%ld",self.model.ID];
    
    [KDAutoRequestTool getMonitorNewsWithParam:self.param success:^(KDGetSubscribeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.infoArr = responseObejct.data;
            [self.currentTabV.header endRefreshing];
            [self.currentTabV reloadData];
         
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
        [self.currentTabV.header endRefreshing];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
    }];
    
}
- (void)loadMoreDetailData{
    self.page = [NSString stringWithFormat:@"%ld",self.page.integerValue+1];
    //    KDSubscribeListParam *param = [[KDSubscribeListParam alloc]init];
    self.param.page = self.page;
    
    [KDAutoRequestTool getMonitorNewsWithParam:self.param success:^(KDGetSubscribeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            if (responseObejct.data.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
                [arr addObjectsFromArray:responseObejct.data] ;
                self.infoArr = arr;
                [self.currentTabV reloadData];
                [self.currentTabV.footer endRefreshing];
            }else{
                [self.currentTabV reloadData];
                [self.currentTabV.footer noticeNoMoreData];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [self.currentTabV.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@",error);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.currentTabV.footer endRefreshing];
    });
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDSubscribCell *cell = [KDSubscribCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDSubscribCell *cell = (KDSubscribCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
        singleCtrl.delegate = self;
        singleCtrl.model = cell.model;
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:singleCtrl animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }
}

#pragma mark - 通知接收区

# pragma mark - KDSubscribCellDelegate
- (void)subscribCell:(KDSubscribCell *)cell collectBtnClick:(UIButton *)collectBtn{
    //0.先判断是点击的收藏还是取消收藏
    if (collectBtn.selected) {//说明是要取消收藏
        [self cancelFavarWithCell:cell andCollectBtn:collectBtn];
    }else{//添加收藏
        [self addFavarWithCell:cell andCollectBtn:collectBtn];
    }
    
    
}
/**
 *  取消收藏 */
- (void)cancelFavarWithCell:(KDSubscribCell *)cell andCollectBtn:(UIButton *)collectBtn{
    __weak __typeof(self)weakSelf = self;
    NSIndexPath *index = [self.currentTabV indexPathForCell:cell];
    KDFavorParam *param = [[KDFavorParam alloc]init];
    param.info_id = [NSString stringWithFormat:@"%ld",cell.model.ID];
    
    [KDCollectRequestTool cancelFavorMsgWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            [SVProgressHUD showSuccessWithStatus:@"取消收藏成功" maskType:SVProgressHUDMaskTypeGradient];
            collectBtn.selected = NO;
            KDSubscribCellModel *model = weakSelf.infoArr[index.row];
            //                        NSMutableArray *muteArr = [NSMutableArray arrayWithArray:weakSelf.infoArr];
            model.isCollection = NO;
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**
 *  添加收藏的一系列操作
 *
 *  @param cell
 */
- (void)addFavarWithCell:(KDSubscribCell *)cell andCollectBtn:(UIButton *)collectBtn{
    __weak __typeof(self)weakSelf = self;
    NSIndexPath *index = [self.currentTabV indexPathForCell:cell];
    //1.弹出收藏夹列表（需要一个拉取收藏夹列表请求）
    KDBaseParam *param = [[KDBaseParam alloc]init];
    [KDCollectRequestTool getFavorTypeListWithParam:param success:^(KDFavorTypeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            AlertTableView *modelView = [[AlertTableView alloc] init];
            __weak typeof(AlertTableView) *weakModelView =modelView;
            
            modelView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            modelView.modalTransitionStyle =  UIModalTransitionStyleCrossDissolve;
            modelView.AlertFromDirect = fromDirectCenter;
            modelView.titleString = @"收藏夹列表";
            modelView.rowHight = 45;
            modelView.viewState = viewStateGray;
            modelView.AlertArray = responseObejct.data;
            
            modelView.doneBtnClickWithType = ^(KDFavorType *selectTyle){
                //2.选中一个收藏夹，返回被选中的文件夹的model！
                KDFavorParam *param = [[KDFavorParam alloc]init];
                param.info_id = [NSString stringWithFormat:@"%ld",cell.model.ID];
                param.post_time = cell.model.craw_publishtime;
                param.type_id = [NSString stringWithFormat:@"%ld", selectTyle.type_id];
                param.url = cell.model.craw_url;
                param.website_name = cell.model.site_name;
                param.author = cell.model.craw_author;
                param.emotionType = [NSString stringWithFormat:@"%ld", cell.model.analy_posneg];
                param.title = cell.model.craw_title;
                //3.添加收藏！
                [KDCollectRequestTool addFavorMsgWithParam:param success:^(KDBaseResult *result) {
                    if ([result.code isEqualToString:@"1"]) {
                        [SVProgressHUD showSuccessWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                        collectBtn.selected = YES;
                        KDSubscribCellModel *model = weakSelf.infoArr[index.row];
                        model.isCollection = YES;
                        
                        [weakModelView dismissSelfView];
                    }else{
                        [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                    }
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
                }];
            };
            
            [weakSelf presentViewController:modelView animated:YES completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**
 *  上报按钮被点击了
 */
- (void)subscribCell:(KDSubscribCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDSubscribCellModel *model = cell.model;
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.url = model.craw_url;
    param.info_title = model.craw_title;
    param.info_content = model.craw_content;
    param.website_type = model.site_type;
    param.website_name = model.site_name;
    reportCtrl.param = param;
//    reportCtrl.type = 1;
    reportCtrl.delegate = self;
    [self.navigationController pushViewController:reportCtrl animated:YES];
}

- (void)subscribCell:(KDSubscribCell *)cell instructBtnClick:(UIButton *)collectBtn{
    
    KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
    singleCtrl.delegate = self;
    singleCtrl.model = cell.model;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [singleCtrl jumpToComment];
        
    });
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:singleCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)subscribCell:(KDSubscribCell *)cell deleteBtnClick:(UIButton *)deleteBtn{
    WS(ws);
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];
    //开启选择界面
    [KGDislikeView showFromView:cell items:[DislikeModel readDislikeReasons] dislikeBlock:^(KGDislikeView *dislikeView, KDDeleteNewsParam *param) {//选完删除原因之后回来会调用这里
        //        KDDeleteNewsParam *param = [[KDDeleteNewsParam alloc]init];
        //        param.method = @"news/del";
        param.ID =[NSString stringWithFormat:@"%ld",  cell.model.ID];
        [SVProgressHUD showWithStatus:@"删除中..." maskType:SVProgressHUDMaskTypeGradient];
        [KDCollectRequestTool deleteNewsWithParam:param success:^(KDBaseResult *responseObejct) {
            if ([responseObejct.code isEqualToString:@"1"]) {
                [SVProgressHUD dismiss];
                [arr removeObjectAtIndex:ip.row];
                ws.infoArr = arr;
                [ws.currentTabV deleteRowsAtIndexPaths:@[ip]withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
        }];
        
        
    }];
}
#pragma mark - KDDetailSubscribControllerDelegate
- (void)backFromDetailSubscribCtrWithModel:(KDSubscribCellModel *)model{
    int index = 0;
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    for (KDSubscribCellModel *cellModel in self.infoArr) {
        if (cellModel.ID == model.ID) {
            [arr replaceObjectAtIndex:index withObject:model];
            break;
        }
        index++;
    }
    self.infoArr = arr;
    [self.currentTabV reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    self.param.keyword = searchText;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.param.keyword = searchBar.text;
    [self.currentTabV.header beginRefreshing];
    //    [searchBar resignFirstResponder];
}


#pragma mark - baseboardDelegate
- (void)baseBoard:(KDBaseBoard *)baseBoard confirmBtnDidClickWithBaseBoardModel:(KDBaseBoardModel *)model{
    KDAccount *account = [KDAccountTool account];
    
    switch (model.regionType) {
        case 1://全国，都不传
            
            break;
        case 2://本省，都不传
            self.param.provinceId = [NSString stringWithFormat:@"%ld", account.provinceId];
            break;
        case 3://本省，都不传
            self.param.provinceId = [NSString stringWithFormat:@"%ld", account.provinceId];
            self.param.cityId = [NSString stringWithFormat:@"%ld", account.cityId];
            break;
        default:
            break;
    }
    self.param.nation = model.subtype;
    self.param.sourceType = model.webSrcType;
    self.param.emotionType = model.docType;
    self.param.isRead = model.isRead;
    self.param.filter = model.filter;
    //    NSDate *date = [self.fmt dateFromString:model.startTime];
    self.param.beginTime = [self.fmt stringFromDate:model.beginDate] ;
    self.param.endTime = [self.fmt stringFromDate:model.endDate];
    //    self.param.endTime = model.endTime;
    [self coverClick:self.cover];
    [self.currentTabV.header beginRefreshing];
    
    
}

#pragma mark - 通知接收区

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
